# coding: utf8

import pdfplumber as ppm
# import pandas as pd


def read_texts_tables(pdfname='score.pdf', password=None):
    texts = []
    tables = []
    with ppm.open(pdfname, password=password) as pdf:
        for pno, page in enumerate(pdf.pages):
            texts.append(page.extract_text())
            tables.append(page.extract_tables())
    return texts, tables


def read_text_tables_at_page(pdfname, pageno=1):
    text, tables = [], []
    with ppm.open(pdfname) as pdf:
        for page in pdf.pages:
            if page.page_number == pageno:
                text = page.extract_text()
                tables = page.extract_tables()
    return text, tables


def read_pdf_metadata(pdfname):
    with ppm.open(pdfname) as pdf:
        print(pdf.metadata)


def extract_images(input_pdf, out_file_prefix='temp'):
    with ppm.open(input_pdf) as pdf:
        for page in pdf.pages:
            for i, img in enumerate(page.images):
                # size = img['width'], img['height']
                data = img['stream'].get_data()
                out_file = f'{out_file_prefix}_page{i}_image{i}.png'
                with open(out_file, 'wb') as fp:
                    fp.write(data)
